package org.example.controller;

import org.example.entity.Menu;
import org.example.entity.Type;
import org.example.entity.User;
import org.example.entity.UserVO;
import org.example.feign.UserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserHandler {

    @Autowired
    public UserFeign userFeign;


    @GetMapping("/findAll")
    @ResponseBody
    public UserVO findAll(@RequestParam("page") int page, @RequestParam("limit") int limit){
        int index = (page-1)*limit;
        UserVO userVO = new UserVO();
        userVO.setCode(0);
        userVO.setMsg("");
        userVO.setCount(userFeign.count());
        userVO.setData(userFeign.findAll(index, limit));
        return userVO;
    }

    @GetMapping("/findById/{id}")
    public ModelAndView findById(@PathVariable("id")long id){
        ModelAndView modelAndView = new ModelAndView();
        User user = userFeign.findById(id);
        modelAndView.setViewName("user_update");
        modelAndView.addObject("user", user);
        return modelAndView;
    }

    @GetMapping("/count")
    public int count(){
        return userFeign.count();
    }

    @PostMapping("/save")
    public String save(User user){
        user.setRegisterdate(new Date());
        userFeign.save(user);
        return "redirect:/menu/redirect/user_manage";
    }

    @PostMapping("/save_user")
    public String save_user(User user){
        user.setRegisterdate(new Date());
        userFeign.save(user);
        return "redirect:/menu/redirect/login";
    }

    @PostMapping("/update")
    public String update(@RequestBody User user){
        userFeign.update(user);
        return "redirect:/menu/redirect/user_manage";
    }

    @GetMapping("/deleteById/{id}")
    public String deleteById(@PathVariable("id")long id){
        userFeign.deleteById(id);
        return "redirect:/menu/redirect/user_manage";
    }

}